import axios from 'axios'
import qs from 'qs'
import store from '../vuex/store.js'
import {bus} from '../bus.js'
/**
 * 定义请求的常量
 * TIME_OUT,ERR_OK
 */
export const TIME_OUT = 10000;//请求超时时间
export const ERR_OK = true;//请求成功返回状态,字段需和后台统一
export const base = process.env.API_ROOT;//基地址 引入全局后台请求地址

axios.defaults.timeout = TIME_OUT  //请求时间
axios.defaults.withCredentials = true  //传递cookie和sessionStorage

//封装请求拦截
 axios.interceptors.request.use(
   config=>{
    //POST传参序列化
   /*  if(config.method === 'post'){
      config.data = qs.stringfy(config.data)
    }*/
    //判断token,配置公共请求头
    let token = window.localStorage.getItem('access-token')
   config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    config.headers['Authorization'] = ''
    if(token != null){// 如果token不为null，否则传token给后台
      config.headers['Authorization'] = token
     }
    store.state.loading = true
    return config
  }, error=>{
       return Promise.reject(error)
   })

//封装响应拦截,判断token是否过期
axios.interceptors.response.use(
  response=>{
    store.state.loading = false
    let {data} = response
    if(data.message === 'token failure!'){ // 如果后台返回的错误标识为token过期，则重新登录
      localStorage.removeItem('token')          // token过期，移除token
      // 进行重新登录操作
      bus.$emit('goto', '/login')
    }
    // 如果http状态码正常，则直接返回数据
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
      return response
    }
  }, error=>{
    store.state.loading = false
    // Do something with response error
    return Promise.reject(error)
  })

//封装通用的方法

export const POST =(url,params) => {
  return axios.post(`${base}${url}`,params).then(res => res.data)
}

export const GET = (url, params) => {
  return axios.get(`${base}${url}`, {
    params: params
  }).then(res => res.data)
}

export const PUT = (url, params) => {
  return axios.put(`${base}${url}`, params).then(res => res.data)
}

export const DELETE = (url, params) => {
  return axios.delete(`${base}${url}`, {
    params: params
  }).then(res => res.data)
}

export const PATCH = (url, params) => {
  return axios.patch(`${base}${url}`, params).then(res => res.data)
}








